/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package wave;

import ast.ASTContent;
import ast.ASTFrontalVar;
import ast.ASTNodalVar;
import ast.ASTTerminalOutput;
import ast.SimpleNode;
import base.TrackNode;
import base.TrackNode.Echo;
import base.Utilities;
import base.Wave;
import base.WaveEnvironment;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Vector;
import trackmsg.EchoMsg;

/**
 *
 * @author Tue
 */
public class ASTTerminalOutputExecution extends WaveExecution{
    public ASTTerminalOutputExecution(WaveHeadParser parser, WaveEnvironment waveEnv){
        super(parser, waveEnv);
    }
    public void execute(ASTTerminalOutput ter, String tail){
        Vector v = getRight(ter);
        System.out.println("[Terminal Output] " + v);
        if(tail.equals("")){
            if(waveEnv.getTrackAddress() != null){
                TrackNode fromTrack = wi.getTrackForest().getTrackNode(waveEnv.getTrackAddress());
                EchoMsg msg = new EchoMsg(fromTrack, Echo.TRUE, waveEnv);
                wi.getTrackQueue().incoming(msg);
            }
        } else {
            Wave newWave = new Wave(tail, new WaveEnvironment(waveEnv));
            wi.getWaveQueue().incoming(newWave);
        }
    }
    private Vector getRight(ASTTerminalOutput ter){
        SimpleNode child = (SimpleNode) ter.jjtGetChild(0);
        Vector v = new Vector();
        Object obj = new Object();
        if (child instanceof ASTFrontalVar){
            obj = waveEnv.getFrontalTable().get(child.getString());
            Utilities.WPPrint("OBJ VALUE: " + obj);
        } else if (child instanceof ASTNodalVar){
            Hashtable<String, Vector> nodalTable =
                    kn.getKNNode(waveEnv.getCONTENT()).getNodalTable(waveEnv.getColor());
            obj = nodalTable.get(child.getString());
        } else if(child instanceof ASTContent) {
            obj = waveEnv.getCONTENT();
        } else {
            obj = child.getString();
        }
        if (obj instanceof Collection){
            v.addAll((Collection)obj);
        } else {
            if(obj != null)
            v.add(obj);
        }
        return  v;
    }
}
